<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
	// 仓库
	import { useUserStore } from '@/stores/user'
	// 第三方库
	import { io, type Socket } from 'socket.io-client'
	// 接口+类型
	import { orderDetailApi, uploadImgApi } from '@/apis/consult'
	import type { OrderDetail } from '@/types/consult.d.ts'
	import type { MsgData, MsgItem } from '@/types/room.d.ts'
	import { nextTick, ref } from 'vue'

	// 组件
	import roomStatusVue from './components/room-status.vue'
	import patientInfoVue from './components/patient-info.vue'
	import notifyInfoVue from './components/notify-info.vue'
	import messageInfoVue from './components/message-info.vue'
	import prescriptionInfoVue from './components/prescription-info.vue'

	// 仓库
	const store = useUserStore()
	// url中的数据默认全部都是字符串
	const props = defineProps<{ orderId: string; payResult: string; type: string }>()

	// 判断支付状态
	if (props.payResult === 'false') {
		uni.switchTab({
			url: '/pages/my/index',
		})
	}

	// 设置 Socket 链接
	// 2. 建立连接
	const socket: Socket = io('https://consult-api.itheima.net', {
		auth: { token: 'Bearer ' + store.token }, // 凭证
		query: { orderId: props.orderId }, // 订单 id
		transports: ['websocket', 'polling'], // 使用协议的优先级
		timeout: 5000, // 超时时间
	})

	socket.on('connect', () => {
		// 建立连接成功
		console.log('连接建立成功')
	})

	socket.on('error', (event) => {
		// 错误异常消息
		console.log('出现错误')
	})

	socket.on('disconnect', () => {
		// 已经断开连接
		console.log('断开连接')
	})

	// 监听订单状态改变
	socket.on('statusChange', () => {
		// console.log('订单状态改变')
		getOrderInfo()
	})

	// 接收历史消息
	const msgList = ref([] as MsgItem)
	socket.on('chatMsgList', (msg: MsgData) => {
		// console.log(msg)

		msg.data?.forEach((item) => {
			// 服务端返回的【数据】如果不满足我们的要求
			// 我们可以 自己 diy
			msgList.value.push(
				{
					msgType: 31,
					msg: { content: item.createTime },
					id: item.createTime,
				},
				...item.items!
			)
		})
		// console.log(msgList.value)
		nextTick(() => {
			// console.log(`item${msgList.value.length}`)
			sp.value = `item${msgList.value.length - 1}`
		})
	})

	// 接收图文消息（医生发过来的消息）
	// 3. 接收回复消息
	socket.on('receiveChatMsg', (message: MsgItem) => {
		// console.log(message)
		// 修改消息为已读
		socket.emit('updateMsgStatus', message.id)
		// 接收到的消息追加到消息列表中
		msgList.value.push(message)
		// 滚到底部 数据更新，UI 更新完毕之后再执行逻辑
		// nextTick 默认用的是微任务，比定时器的优先级要高
		nextTick(() => {
			// console.log(`item${msgList.value.length}`)
			sp.value = `item${msgList.value.length - 1}`
		})
	})

	// 获取订单信息
	const orderInfo = ref({} as OrderDetail)
	const getOrderInfo = async () => {
		const res = await orderDetailApi(props.orderId)
		// console.log(res)
		orderInfo.value = res
	}
	getOrderInfo()

	// 聊天信息
	const iptMsg = ref('')

	// 发送信息
	const sendMsg = () => {
		if (iptMsg.value.trim() === '') return
		console.log(store.userId)
		socket.emit('sendChatMsg', {
			from: store.userId,
			to: orderInfo.value.docInfo.id,
			msgType: 1,
			msg: {
				content: iptMsg.value,
			},
		})
		// console.log(iptMsg.value)
		iptMsg.value = ''
	}

	// 图片信息
	const imgMessage = async () => {
		if (orderInfo.value.status >= 4) return

		// 选图片
		const res = await uni.chooseImage()
		// console.log(res)
		const path = res.tempFilePaths[0]
		// 传图片
		const uploadRes = await uploadImgApi(path)
		// 发消息
		socket.emit('sendChatMsg', {
			from: store.userId,
			to: orderInfo.value.docInfo.id,
			msgType: 4, // 4图片，1 文字
			msg: {
				picture: uploadRes,
			},
		})
	}

	// 滚到指定的元素位置
	const sp = ref('')

	// const scrollToItem = () => {
	// 	sp.value = 'item14'
	// }
</script>

<template>
	<view class="room-page">
		<roomStatusVue
			:status="orderInfo.status"
			:statusValue="orderInfo.statusValue"
			:countdown="orderInfo.countdown"
		></roomStatusVue>
		<!-- <button @tap="scrollToItem">滚动</button> -->
		<scroll-view
			refresher-enabled
			refresher-background="#f2f2f2"
			scroll-y
			style="flex: 1; overflow: hidden"
			:scroll-into-view="sp"
		>
			<!-- <view class="message-container"> -->
			<!-- 此处将来填充更多代码... -->
			<view v-for="(item, index) in msgList" :id="'item' + index">
				<patientInfoVue v-if="item.msgType === 21" :info="item.msg.consultRecord">
				</patientInfoVue>
				<notifyInfoVue
					v-if="item.msgType === 31 || item.msgType === 32"
					:type="item.msgType"
				>
					<!-- <text style="color: skyblue; background-color: orange"> -->
					{{ item.msg.content }}
					<!-- </text> -->
				</notifyInfoVue>
				<!-- 图文信息 -->
				<messageInfoVue
					v-if="item.msgType <= 4"
					:type="item.msgType"
					:msgItem="item"
				></messageInfoVue>
				<!-- 处方信息 -->
				<prescriptionInfoVue
					v-if="item.msgType === 22"
					:preInfo="item.msg.prescription"
				></prescriptionInfoVue>
			</view>
			<!-- </view> -->
		</scroll-view>

		<!-- 发送消息 -->
		<view class="message-bar">
			<template v-if="true">
				<uni-easyinput
					:disabled="orderInfo.status === 4"
					:clearable="false"
					:input-border="false"
					placeholder-style="font-size: 32rpx; color: #c3c3c5;"
					placeholder="问医生"
					v-model="iptMsg"
					@confirm="sendMsg"
				/>
				<view @tap="imgMessage" class="image-button">
					<uni-icons size="40" color="#979797" type="image"></uni-icons>
				</view>
			</template>
			<button v-else class="uni-button">咨询其它医生</button>
		</view>
	</view>
</template>

<style lang="scss">
	@import './index.scss';
</style>
